package com.wwwc.index.servlet;

import java.io.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;

import com.wwwc.util.web.*;
import com.wwwc.index.ejb.EJBManager;
import com.wwwc.index.ejb.forum.*;
import com.wwwc.index.ejb.user.*;

public class ForumAddNewServlet extends HttpServlet {
    private User u_ejbDb;
    private Forum f_ejbDb;
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
	try {
	    response.setContentType("text/html");
	    PrintWriter out        = response.getWriter();
	    HttpSession session    = request.getSession(true);
	    
	    String call_path       = request.getContextPath()+request.getServletPath();
	    String user_ip         = request.getRemoteAddr();

	    String lid = (String)session.getAttribute("lid");
	    if(lid == null) {
		lid = "en";
	    }

	    ResourceBundle message = (ResourceBundle)session.getAttribute("ForumMessage_"+lid);
	    if (message == null) {
		try{
		    message = ResourceBundle.getBundle("Forum_"+lid);
		    session.setAttribute("ForumMessage_"+lid, message);
		}
		catch(Exception e) {
		    System.out.println(e);
		    return;
		}
	    }

	    //==================================================================================
	    // Globe info
	    //==================================================================================

	    UserProfile user_profile = (UserProfile)session.getAttribute("UserProfile");
	    DirectoryDetails dd = (DirectoryDetails)session.getAttribute("LastDirectoryDetails_"+lid);

	    //==================================================================================
	    // Forum (directory)  info
	    //==================================================================================
	    String table_name  = request.getParameter("table_name");
	    String title_max   = request.getParameter("title_max");
	    String text_max    = request.getParameter("text_max");
	    String link_max    = request.getParameter("link_max");
	    String image_max   = request.getParameter("image_max");

	    if(table_name == null) {
		System.out.print("ForumAddNewServlet:101:missing parameter:[table_name]");
		System.out.println("[title_max][text_max][link_max][image_max]");
		return;
	    }

	    int title_size = 400;
	    int text_size  = 1024*5000;
	    int link_size  = 2000;
	    int image_size = 2000;

	    try {
		if(title_max != null)
		title_size = Integer.parseInt(title_max);
		if(text_max != null)
		text_size  = Integer.parseInt(text_max);
		if(link_max != null)
		link_size  = Integer.parseInt(link_max);
		if(image_max != null)
		image_size = Integer.parseInt(image_max);
	    }
	    catch (Exception e) {
		System.out.println("ForumAddNewServlet:Error:102:"+e);
	    }

	    //====================================================================================
	    // for request include (used to communicat between parent servlet and this servlet)
	    //====================================================================================
	    String error_call_back_name    = (String)request.getAttribute("errorCallBackName");
	    String error_call_back_value   = (String)request.getAttribute("errorCallBackValue");
	    String savedMessage            = (String)request.getAttribute("savedMessage");

	    //====================================================================================
	    // parent ForumDetails set by caller if is a reply
	    //====================================================================================
	    ForumDetails pfd = (ForumDetails)request.getAttribute("ParentForumDetails");

	    int file_id             = -1;
	    String dir_id           = dd.getId();
	    int    fd_gid           = -1;
	    int    fd_position      = 0;
	    int    fd_pid           = -1;
	    int treply              = 0;
	    String path             = ""; 
	    int size                = 0;
	    int readers             = 0;
	    float rating            = 0.0f;
	    Date date               = new Date();
	    String title            = "";
	    String poster           = "";
	    String password         = "";
	    String text             = "";
	    String image            = "";
	    String link             = "";
	    boolean allow_reply     = true;
	    boolean on_top          = false;
	    boolean removed         = false;
	    //String user_ip

	    if(pfd != null) {
		fd_gid           = pfd.getGroupId();
		fd_position      = 1+pfd.getPosition();
		fd_pid           = pfd.getFileId();
		path             = pfd.getPath(); 
		title            = "Re:"+pfd.getTitle();
	    }

	    String add_new_post = request.getParameter("submit_post");
	    String error = null;
	     
	    if(add_new_post != null) {
		String submit_id  = request.getParameter("submit_id");
		if(submit_id == null) {
		    return;
		}
		else if(submit_id.equals(session.getAttribute("submited_id"))) {		
		    out.println("<TABLE align=center>");
		    out.println("<TR><TD><img src=/images/star.gif></TD>");
		    out.println("<TD><I>Your post has been saved. Please do not re-submit!</I></TD></TR>");
		    out.println("</TABLE>");
		    return;
		} 

		fd_pid          = Integer.parseInt(request.getParameter("fd_pid"));
		fd_gid          = Integer.parseInt(request.getParameter("fd_gid"));
		fd_position     = Integer.parseInt(request.getParameter("fd_position"));
		
		title            = request.getParameter("title");
		poster           = request.getParameter("username");
		password         = request.getParameter("password");
		text             = request.getParameter("text");
		image            = request.getParameter("image");
		link             = request.getParameter("link");
		allow_reply      = true;
		on_top           = false;

		//===========================================================================
		// Error check
		//===========================================================================
		
		if(error == null) {
		    if(user_profile == null) {
			if((poster == null || poster.length() > 0) && password != null && password.length()>0) {
			    try {
				if (u_ejbDb == null) {
				    u_ejbDb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
				}
				if(!u_ejbDb.usernamePasswordCheck(poster, password)) {
				    error = "Username and Password check error!";
				}
			    }
			    catch (Exception e) {
				System.out.println("ForumAddNewServlet:usernameAndPasswordCheck:Error:"+e);
			    }
			}
		    }
		}
		
		if(error == null && (title == null || title.length()==0)) {
		    error = message.getString("TitleIsRequired")+".";
		}

		if(error == null &&  title.length() > title_size) {
		    error = message.getString("TitleIsTooLong")+".";
		}

		if(error == null) {
		    if(text != null && text.length() > text_size) {
			error = message.getString("TextIsTooLong")+"("+text_size+").";
		    }
		}

		if(error == null) {
		    if(link != null && link.length() > link_size) {
			error = message.getString("LinkIsTooLong")+"("+link_size+").";
		    }
		}

		if(error == null) {
		    if(title.indexOf("\"") != -1) {
			title = title.replaceAll("\"","&quot;");
		    }
		}

		if(error == null && pfd != null && title.equals("Re:"+pfd.getTitle()) && 
		   text.length()==0 && link.length()==0 && image.length()==0) {
		    error = message.getString("NoData")+"!";
		}

		/*
		if(!MyUserInputCheck.isUrl(url)) {
		    return (errorInfo.getString("Field")+" ["+field_name+"] "+
			    errorInfo.getString("ConnectTo")+" ["+url+"] "+errorInfo.getString("error")+".");
		}
		*/

		if(error == null) {
		    try{
			if (f_ejbDb == null) {
			    f_ejbDb = (Forum)EJBManager.getEJB("java:comp/env/ejb/ForumEJB", "Forum");
			}

			size = text.length();

			if(user_profile != null) {
			    poster = user_profile.getUserName();
			}

			error = f_ejbDb.addNewForum(table_name, dir_id, fd_gid, fd_position,
						    fd_pid, treply, path, size, readers, rating, date, title, 
						    poster, text, image, link, allow_reply, on_top, removed, user_ip);

			if(error == null) {
			    session.setAttribute("submited_id", submit_id);

			    out.println("\n<SCRIPT>");
			    out.println("\n\t top.location.replace(\""+call_path+"\");");
			    out.println("\n</SCRIPT>");
			    return;
			}
			else {
			    System.out.println(error);
			    error = "Sorry. Save data error! Please try again.";
			}
		    }
		    catch(Exception e) {
			System.out.println("ForumServlet:saveNewPost:Error:"+e);
		    }
		}
	    }

	    String submit_id = System.currentTimeMillis()+"";
	    session.setAttribute("submit_id", submit_id);

	    StringBuffer sbf = new StringBuffer();
	    sbf.append("\n<FORM method=\"post\" name=\"postform\"  action=\""+call_path+"\">");
	    sbf.append("\n<TABLE  cellSpacing=\"0\" cellPadding=\"0\" border=1 align=center>");
	    if(error != null) {
		sbf.append("\n<TR><TD align=center><img src=/images/star.gif><I>"+error+"</I></TD></TR>");
	    }
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align=center>");
	    
	    if(user_profile == null) {
		sbf.append("\n<TABLE cellSpacing=\"3\" cellPadding=\"3\" border=0 align=center>");
		sbf.append("\n<TR>");
		sbf.append("\n<TD align=right>"+message.getString("userName")+":</TD>");
		sbf.append("\n<TD align=left><input type=\"text\" name=\"username\" size=\"15\" maxLength=\"20\"></TD>");
		sbf.append("\n<TD align=left>"+message.getString("password")+":</TD>");
		sbf.append("\n<TD align=left><input type=\"password\" name=\"password\" size=\"15\" maxLength=\"20\" value=\"\"></TD>");
		sbf.append("\n<TD align=center>");
		sbf.append("(Optional)");
		sbf.append("</TD>");
		sbf.append("\n</TR>");
		sbf.append("\n</TABLE>");
	    }
	    else {
		sbf.append("\n<TABLE cellSpacing=\"3\" cellPadding=\"3\" border=0 align=center>");
		sbf.append("\n<TR>");
		sbf.append("\n<TD align=center>"+message.getString("userName")+":</TD>");
		sbf.append("\n<TD align=center>");
		sbf.append(user_profile.getUserName());
		sbf.append("</TD>");
		sbf.append("\n</TR>");
		sbf.append("\n</TABLE>");
	    }

	    sbf.append("\n</TD></TR>");

	    sbf.append("\n<TR><TD align=center>");

	    sbf.append("\n<TABLE cellSpacing=\"5\" cellPadding=\"5\" border=0 align=center>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align=\"right\">"+message.getString("title")+":</TD>");
	    sbf.append("\n<TD align=\"left\" clospan=3>");
	    sbf.append("\n<input type=\"text\" name=\"title\" value=\""+title+"\" size=\"65\" maxLength=\"100\"></TD>");
	    sbf.append("\n</TR>");
	
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align=\"right\">"+message.getString("text")+":</TD>");
	    sbf.append("<TD align=\"left\"><TEXTAREA name=\"text\" rows=\"6\" cols=\"48\" value=\"\">"+text+"</TEXTAREA></TD>");
	    sbf.append("\n</TR>");

	    //link
	    sbf.append("\n<input type=hidden name=link value="+link+">");
	    //sbf.append("\n<TR>");
	    //sbf.append("\n<TD align=\"right\">"+message.getString("text")+":</TD>");
	    //sbf.append("<TD align=\"left\"><TEXTAREA name=\"text\" rows=\"6\" cols=\"48\" value=\"\">"+text+"</TEXTAREA></TD>");
	    //sbf.append("\n</TR>");
	    //image
	    sbf.append("\n<input type=hidden name=image value="+image+">");
	    //sbf.append("\n<TR>");
	    //sbf.append("\n<TD align=\"right\">"+message.getString("text")+":</TD>");
	    //sbf.append("<TD align=\"left\"><TEXTAREA name=\"text\" rows=\"6\" cols=\"48\" value=\"\">"+text+"</TEXTAREA></TD>");
	    //sbf.append("\n</TR>");

	    sbf.append("\n</TABLE>");

	    sbf.append("\n</TD></TR>");
	    sbf.append("\n<TR><TD align=center>");

	    sbf.append("\n<TABLE  cellSpacing=\"5\" cellPadding=\"5\" border=0 align=center>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align=\"center\">");
	    sbf.append("<input type=\"submit\"  name=\"submit_post\" value=\""+message.getString("submit")+"\"");
	    sbf.append(" style=\"font-size: 8pt\">");
	    sbf.append("\n<input type=\"reset\" name=\"B2\" value=\""+message.getString("reset")+"\" style=\"font-size: 8pt\">");
	    sbf.append("\n</TD></TR>");
	    sbf.append("\n</TABLE>");

	    sbf.append("\n</TD></TR>");
	    sbf.append("\n</TABLE>");

	    sbf.append("\n<input type=hidden name="+error_call_back_name+" value="+error_call_back_value+">");
	    sbf.append("\n<input type=hidden name=fd_pid value="+fd_pid+">");
	    sbf.append("\n<input type=hidden name=fd_gid value="+fd_gid+">");
	    sbf.append("\n<input type=hidden name=fd_position value="+fd_position+">");
	    sbf.append("\n<input type=hidden name=submit_id value="+submit_id+">");
	    sbf.append("\n</FORM><BR>");

	    out.println(sbf);
	}
	catch(IOException e) {
	    System.out.println("ForumAddNewServlet:Error:IOException:"+e);
	}
	catch(Exception e) { 
	    System.out.println("ForumAddNewServlet:Error:Exception:"+e);
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
	doPost(request, response);
    }
}






